﻿using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LuShanTea.Web.Common
{
    public class RedisHelper
    {
        private IDatabase _dataBase = null;

        public RedisHelper(IDatabase database)
        {
            _dataBase = database;
        }

        public void Add(string key, object value)
        {

            if (!string.IsNullOrEmpty(key) && value != null)
            {
                //添加前先删除选优数据
                if (_dataBase.KeyExists(key))
                {
                    _dataBase.KeyDelete(key);
                }

                _dataBase.StringSet(key, JsonConvert.SerializeObject(value));
            }
        }

        public string Get(string key)
        {
            try
            {
                if (!string.IsNullOrEmpty(key))
                {

                    return _dataBase.StringGet(key).ToString();
                }
                else
                {
                    return "";
                }
            }
            catch
            {

                return "";
            }
        }

        public T[] Get<T>(string key)
        {
            try
            {
                if (!string.IsNullOrEmpty(key))
                {

                    return JsonConvert.DeserializeObject<T[]>(_dataBase.StringGet(key));
                }
                else
                {
                    return default(T[]);
                }
            }
            catch
            {

                return default(T[]);
            }
        }
    }
}
